"use client"

import { useCallback, useState } from "react"
import { useRouter } from "next/navigation"
import { useHistory } from "@/components/history-context"
import { ImageIcon, Loader2Icon, UploadCloudIcon } from "lucide-react"
import { useDropzone } from "react-dropzone"
import axios from "axios"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"

const server_url = "http://127.0.0.1:5003"

export function ImageUploader() {
  const router = useRouter()
  const { addHistory } = useHistory()
  const [file, setFile] = useState<File | null>(null)
  const [preview, setPreview] = useState<string | null>(null)
  const [uploading, setUploading] = useState(false)
  const [progress, setProgress] = useState(0)
  const [result, setResult] = useState<any>(null)
  const [errorMsg, setErrorMsg] = useState<string>("")
  const [modalOpen, setModalOpen] = useState(false)
  const [modalImg, setModalImg] = useState<string | null>(null)

  const onDrop = useCallback((acceptedFiles: File[]) => {
    if (acceptedFiles.length > 0) {
      const selectedFile = acceptedFiles[0]
      setFile(selectedFile)

      const objectUrl = URL.createObjectURL(selectedFile)
      setPreview(objectUrl)

      return () => URL.revokeObjectURL(objectUrl)
    }
  }, [])

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      "image/*": [".jpeg", ".jpg", ".png", ".gif", ".webp"],
    },
    maxFiles: 1,
  })

  const handleUpload = async () => {
    if (!file) return
    setUploading(true)
    setErrorMsg("")
    setResult(null)
    setProgress(0)

    const timer = setInterval(() => {
      setProgress((prev) => (prev + 33 < 99 ? prev + 33 : 99))
    }, 30)

    try {
      const param = new FormData()
      param.append("file", file, file.name)
      const response = await axios.post(server_url + "/upload", param, {
        headers: { "Content-Type": "multipart/form-data" },
      })
      setProgress(100)
      clearInterval(timer)
      setResult(response.data)
      if (response.data && response.data.result) {
        addHistory(response.data.result)
      }
    } catch (err: any) {
      setErrorMsg("上传失败")
      clearInterval(timer)
      setProgress(0)
    }
    setUploading(false)
  }

  const resetUpload = () => {
    setFile(null)
    setPreview(null)
    setProgress(0)
    setResult(null)
    setErrorMsg("")
  }

  const handleDownload = (url: string, filename: string) => {
    const link = document.createElement("a")
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  const handleEnlarge = (url: string) => {
    setModalImg(url)
    setModalOpen(true)
  }

  const closeModal = () => {
    setModalOpen(false)
    setModalImg(null)
  }

  return (
    <div className="flex flex-col gap-4">
      <Card className="border-dashed shadow-sm">
        <CardContent className="p-4 md:p-6">
          {!file ? (
            <div
              {...getRootProps()}
              className={`flex flex-col items-center justify-center gap-4 rounded-lg border-2 border-dashed border-muted-foreground/25 p-8 md:p-12 text-center transition-colors ${
                isDragActive ? "border-primary/50 bg-muted/50" : ""
              }`}
            >
              <input {...getInputProps()} />
              <div className="flex h-20 w-20 items-center justify-center rounded-full bg-muted">
                <UploadCloudIcon className="h-10 w-10 text-muted-foreground" />
              </div>
              <div className="space-y-2">
                <p className="text-xl font-medium">{isDragActive ? "放开以上传照片" : "点击上传"}</p>
                <p className="text-muted-foreground">支持 JPG, PNG, GIF 格式，最大 10MB</p>
              </div>
              <Button variant="outline" size="lg" disabled={isDragActive} className="mt-2">
                <ImageIcon className="mr-2 h-5 w-5" />
                选择照片
              </Button>
            </div>
          ) : (
            <div className="flex flex-col gap-6">
              <div className="flex items-center justify-center">
                {preview && (
                  <div className="relative overflow-hidden rounded-lg border">
                    <img
                      src={preview || "/placeholder.svg"}
                      alt="预览"
                      className="max-h-[400px] w-auto object-contain"
                    />
                  </div>
                )}
              </div>
              <div className="flex flex-col gap-2">
                <div className="flex items-center justify-between">
                  <p className="text-sm font-medium">{file.name}</p>
                  <p className="text-sm text-muted-foreground">{(file.size / (1024 * 1024)).toFixed(2)} MB</p>
                </div>
                {uploading && <Progress value={progress} className="h-2 w-full" />}
                {errorMsg && <p className="text-red-500 text-sm mt-2">{errorMsg}</p>}
              </div>
              <div className="flex flex-wrap gap-2">
                {!uploading ? (
                  <>
                    <Button onClick={handleUpload}>
                      <UploadCloudIcon className="mr-2 h-4 w-4" />
                      开始检测
                    </Button>
                    <Button variant="outline" onClick={resetUpload}>
                      重新选择
                    </Button>
                  </>
                ) : (
                  <Button disabled>
                    <Loader2Icon className="mr-2 h-4 w-4 animate-spin" />
                    正在处理...
                  </Button>
                )}
              </div>
              {result && (
                <div className="mt-6">
                  <div className="flex flex-col md:flex-row gap-6">
                    <div className="flex flex-col items-center">
                      <p className="font-semibold text-center mb-2">原始图像</p>
                      <img
                        src={result.image_url || "/placeholder.svg"}
                        alt="原图"
                        className="max-w-full md:max-w-xs rounded border cursor-zoom-in"
                        onClick={() => handleEnlarge(result.image_url)}
                      />
                      <div className="flex gap-2 mt-2">
                        <button
                          className="px-3 py-1 rounded bg-secondary text-sm"
                          onClick={() => handleDownload(result.image_url, "original.jpg")}
                        >
                          下载
                        </button>
                      </div>
                    </div>
                    <div className="flex flex-col items-center">
                      <p className="font-semibold text-center mb-2">检测结果</p>
                      <img
                        src={result.draw_url || "/placeholder.svg"}
                        alt="检测图"
                        className="max-w-full md:max-w-xs rounded border cursor-zoom-in"
                        onClick={() => handleEnlarge(result.draw_url)}
                      />
                      <div className="flex gap-2 mt-2">
                        <button
                          className="px-3 py-1 rounded bg-secondary text-sm"
                          onClick={() => handleDownload(result.draw_url, "result.jpg")}
                        >
                          下载
                        </button>
                      </div>
                    </div>
                  </div>
                  {modalOpen && (
                    <div
                      className="fixed inset-0 z-50 flex items-center justify-center bg-black/70"
                      onClick={closeModal}
                    >
                      <div
                        className="bg-white rounded-lg p-4 max-w-3xl max-h-[90vh] flex flex-col items-center"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <img src={modalImg || ""} alt="放大预览" className="max-h-[80vh] w-auto object-contain" />
                        <button className="mt-4 px-4 py-2 bg-primary text-white rounded" onClick={closeModal}>
                          关闭
                        </button>
                      </div>
                    </div>
                  )}
                  <div className="mt-4">
                    <p className="font-semibold mb-2">检测目标</p>
                    <div className="overflow-x-auto">
                      <table className="w-full border text-center">
                        <thead>
                          <tr>
                            <th className="border px-2 py-1">目标类别</th>
                            <th className="border px-2 py-1">目标大小</th>
                            <th className="border px-2 py-1">置信度</th>
                          </tr>
                        </thead>
                        <tbody>
                          {Object.keys(result.image_info).map((key, idx) => (
                            <tr key={idx}>
                              <td className="border px-2 py-1">{key}</td>
                              <td className="border px-2 py-1">{result.image_info[key][0]}</td>
                              <td className="border px-2 py-1">{result.image_info[key][1]}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
